import gugga.collections.ArrayList;

import test_framework.test.unit.TestCase;
import test_framework.env.reflect.ClassInfo;

/**
 * @author vladimir
 */
class guggaLibTests.support.TaskTestCase 
		extends TestCase
{
	private var delayID:Number;
	private var delayPeriod:Number;
	
	private var paused:Boolean;
	
	private var taskRegister:ArrayList;
	private var requiredTaskStatuses:ArrayList;
	
	public function TaskTestCase()
	{
		super();
		this.paused = false;
		
		this.taskRegister = new ArrayList();
		this.requiredTaskStatuses = new ArrayList();
	}
	
	private function resetTaskTest()
	{
		this.paused = false;
		
		this.taskRegister = new ArrayList();
		this.requiredTaskStatuses = new ArrayList();
	}
	
	private function onTaskStarted(aEvent:Object)
	{
		this.taskRegister.addItem({task:aEvent.target, event:"start"});
	}
	
	private function onTaskCompleted(aEvent:Object)
	{
		this.taskRegister.addItem({task:aEvent.target, event:"completed"});
	}
	
	private function onTaskInterrupted(aEvent:Object)
	{
		this.taskRegister.addItem({task:aEvent.target, event:"interrupted"});
	}
	
	private function pauseToEvaluateTaskExecution()
	{
		this.paused = true;
		this.pause();
	}
	
	private var EVALUATE_TASK_EXECUTION_METHOD_NAME:String 
		= "evaluateTaskExecution";
	
	private function evaluateTaskExecution()
	{
		clearInterval(this.delayID);
		
		for(var i = 0; i < requiredTaskStatuses.length; i++)
		{
			var taskInfo:ClassInfo 
				= ClassInfo.forInstance(requiredTaskStatuses[i].task);
			assertTrue(
					"undefined task found - event source:" + taskInfo.getName() + "; expected status:" + requiredTaskStatuses[i].event + "(on iteration " + i + ")",
					this.taskRegisterContains(requiredTaskStatuses[i]));
		}
		
		if(this.paused)
		{
			this.paused = false;
			this.resume();
		}
	}
	
	private function taskRegisterContains(aRequiredTaskStatus:Object) : Boolean
	{
		for(var i = 0; i < taskRegister.length; i++)
		{
			var taskStatus:Object = taskRegister[i];
			if(aRequiredTaskStatus.task == taskStatus.task
				&& aRequiredTaskStatus.event == taskStatus.event)
			{
				return true;
			}
		}
		
		return false;
	}
	
	private function taskRegisterEqualsRequiredTasks() : Boolean
	{
		return taskRegister.length == requiredTaskStatuses.length;
	}
	
	private function assertTaskRegisterIsEmpty(aMessage:String) : Boolean
	{
		return assertTrue(aMessage, taskRegister.isEmpty());
	}
	
	private function printInLogTaskRegisterContent() : Boolean
	{
		var message:String;
		for(var i = 0; i < taskRegister.length; i++)
		{
			var taskInfo:ClassInfo 
				= ClassInfo.forInstance(taskRegister[i].task);
			message += "\ntask: " + taskInfo.getName();
			message += "; status: " + taskRegister[i].event + ";";
		}
		
		return assertTrue(message, false);
	}
}